/**
 * 弹窗配置
 */
import audio from '@system.audio'
import device from '@system.device'
let that = null,
  $animation = null
const getCodeData = async (_this, code = 'CommonNative_K6DFO7PF') => {
  that = _this
  let result = await TACTICS_SDK_UTILS.getPopupConfigByPopupCode(
    code,
    that.customAction.popKey || ''
  )
  LOG('CUSTOM', `getCodeData==>result`, result)
  if (!result) {
    that.$emit('eventWatch', {
      popData: { popConfig: that.curpopConfig, advConfig: that.nativeAdvObj },
      index: that.index,
      eventName: 'closePopData',
      action: 'popCodeError',
      actionCode: that.actionCode,
      customAction: that.customAction,
    })
    return
  }
  result = getFeature(result, code)
  LOG('CUSTOM', `getFeature==>result`, result)
  result = Object.assign({}, result, { actionCode: that.actionCode })
  setDataConfig(result, code)
  that.curpopConfig = result
  if (that.nativeAdvObj.styleType == 'renderer' && that.curpopConfig.commonStyle.new_is_full_screen) {
    // 自渲染全屏点击区域位置随机
    nativeScreenPos()
  }
  if (that.popMovieType) {
    setTimeout(() => {
      that.nativeIsShowPop = true
      that.nativeIsShowPopPos = true
      popAnimation()
    }, result.commonStyle.transitionBeforeTime)
    // 素材位置在屏幕顶、底部时
    setTimeout(() => {
      that.material_display = true
    }, result.commonStyle.transitionBeforeTime + 500)
  } else {
    that.material_display = true
    that.nativeIsShowPop = true
    setTimeout(() => {
      //广告更换父级，广告素材模块闪烁问题
      that.nativeIsShowPopPos = true
    }, 0)
  }
  popBeforeShowGif(that.curpopConfig)
  TACTICS_SDK.sePopupShowTimes(code)
  that.$emit('eventWatch', {
    popData: { popConfig: that.curpopConfig, advConfig: that.nativeAdvObj },
    index: that.index,
    eventName: 'popShow',
    action: 'popShow',
    actionCode: that.actionCode,
    customAction: that.customAction,
  })
  initViewShow(that.curpopConfig)
  // 广告拿取上报
  AD_SDK.uploadAdInfo('take', that.nativeAdvObj)
  POP_TOOLS.resetActionPopType()
  reportShowPop()
}
// 弹窗相关配置-数据相关
const setDataConfig = (curConfig, code) => {
  that.nativeAdvObj.popName = curConfig.popName
  that.nativeAdvObj.popGroupName = curConfig.popGroupName
  // vivo正向按钮添加前后缀
  const btnFix = curConfig.btnStyle.btnFontFix.split(',')
  that.nativeAdvObj.clickBtnTxt =
    btnFix[0] +
    that.nativeAdvObj.advDetail.clickBtnTxt +
    (btnFix.length > 1 ? btnFix[1] : '')
  if (curConfig.menubarStyle.isShow) {
    getMenuData()
  }
  // 弹窗入场动画类型
  if (!that.isShowSkeleton && curConfig.configBaseFormData.popup_movie_type) {
    that.popMovieType = curConfig.configBaseFormData.popup_movie_type
  }
}
/**
 * 计算弹窗数据
 */
const getFeature = (popConfig, code) => {
  let curConfig = Object.assign({}, popConfig)
  let popScaleNum = parseFloat(popConfig.commonStyle.scale)
  let configArr = [
    'btnStyle:font|hotAbout|hotBottom|hotTop|left|radio|top|btn_material_width|btn_material_height|btn_material_font|btn_material_left|btn_material_top|btn_material_radius|material_hot_about|material_hot_bottom|material_hot_top',
    'closeStyle:top|distance',
    'negStyle:font|left|top',
    'popStyle:',
    'materialStyle:top',
    'crowdStyle:between|distance|font',
    'guidingGesture:guiding_gesture_top|guiding_gesture_left|guiding_gesture_width|guiding_gesture_height',
  ]
  for (let i = 0; i < configArr.length; i++) {
    let item = configArr[i].split(':')
    let attrs = item[0]
    let attrVal = item[1] && item[1].split('|')
    setBtnWH(curConfig, attrs, popScaleNum)
    for (let n = 0; n < attrVal.length; n++) {
      curConfig[attrs][attrVal[n]] =
        Number(curConfig[attrs][attrVal[n]]) * popScaleNum
    }
    if (attrs == 'btnStyle' && that.btnType == 3) {
      curConfig.btnStyle.font = 0
    }
  }
  curConfig.btnStyle.btn_material_img =
    curConfig.commonStyle.btn_material_img
  return curConfig
}
/**
* 自渲染全屏状态水平位置 
* 在可视范围内，除去点击区域宽高，随机位置
* 水平最小差值30px，垂直最小差值80px
*/
const nativeScreenPos = () => {
  // 18 = （750 - 点击区域宽）/ 30
  that.leftPos = Math.floor(Math.random() * 18) * 30;
  // 360 = 2*点击区域高度
  const height = Math.floor((that.screenHeight - 360) / 80);
  that.topPos = Math.floor(Math.random() * height) * 80;
}
// 限制厂商按钮宽高
const setBtnWH = (curConfig, attrs, popScaleNum = 1) => {
  if (attrs == 'guidingGesture') {
    return
  }
  if (that.btnAdb == 2 && attrs == 'btnStyle') {
    let widthBrand = 90
    heightBrand = 180
    const widthBtn = Number(curConfig.btnStyle.width) * popScaleNum
    const heightBtn = Number(curConfig.btnStyle.height) * popScaleNum
    curConfig.btnStyle.width = widthBtn < widthBrand ? widthBrand : widthBtn
    curConfig.btnStyle.height =
      heightBtn > heightBrand ? heightBrand : heightBtn
  } else {
    curConfig[attrs].width = Number(curConfig[attrs].width) * popScaleNum
    curConfig[attrs].height = Number(curConfig[attrs].height) * popScaleNum
  }
}
/**
 * 弹窗入场动画
 * popup_movie_type: 0默认，1上入，2下入
 */
const popAnimation = () => {
  // 弹窗入场动画
  let keyframes = []
  // 上入
  if (that.popMovieType == 1) {
    keyframes = [
      {
        transform: {
          translateY: `0`,
        },
        time: 0,
      },
      {
        transform: {
          translateY: `${that.screenHeight}px`,
        },
        time: 100,
      },
    ]
  } else if (that.popMovieType == 2) {
    // 下入
    keyframes = [
      {
        transform: {
          translateY: `0`,
        },
        time: 0,
      },
      {
        transform: {
          translateY: `-${that.screenHeight}px`,
        },
        time: 100,
      },
    ]
  }
  let options = {
    duration: 250,
    easing: 'ease-in-out',
    fill: 'forwards',
  }
  try {
    that.$nextTick(() => {
      setTimeout(() => {
        executeAnimation(keyframes, options)
      }, 0)
    })
  } catch (error) {
    setTimeout(() => {
      executeAnimation(keyframes, options)
    }, 50)
  }
}
// 执行动画
const executeAnimation = (keyframes, options) => {
  const cAnimationNode = that.$element('popAnimation')
  if (cAnimationNode) {
    $animation = cAnimationNode.animate(keyframes, options)
    $animation.play()
  } else {
    that.popMovieType = 0
  }
}
/**
 * 添加页面拦截器
 */
const initViewShow = (popConfig) => {
  // 关闭按钮拦截器
  if (popConfig.closeStyle.delay > 0) {
    that.delayConfig.close.timer = setTimeout(() => {
      that.delayConfig.close.type = true
      clearTimeout(that.delayConfig.close.timer)
      that.delayConfig.close.timer = null
    }, popConfig.closeStyle.delay)
  } else {
    that.delayConfig.close.type = true
  }
  // 挤动文案拦截器
  if (popConfig.crowdStyle.delay > 0) {
    that.delayConfig.crowd.timer = setTimeout(() => {
      that.delayConfig.crowd.type = true
      clearTimeout(that.delayConfig.crowd.timer)
      that.delayConfig.crowd.timer = null
    }, popConfig.crowdStyle.delay)
  } else {
    that.delayConfig.crowd.type = true
  }
  // 负向按钮拦截器
  if (popConfig.negStyle.delay > 0) {
    that.delayConfig.neg.timer = setTimeout(() => {
      that.delayConfig.neg.type = true
      clearTimeout(that.delayConfig.neg.timer)
      that.delayConfig.neg.timer = null
    }, popConfig.negStyle.delay)
  } else {
    that.delayConfig.neg.type = true
  }
  // 物理返回拦截器
  if (popConfig.commonStyle.backLockTime > 0) {
    that.delayConfig.backPress.timer = setTimeout(() => {
      that.delayConfig.backPress.type = true
      clearTimeout(that.delayConfig.backPress.timer)
      that.delayConfig.backPress.timer = null
    }, popConfig.commonStyle.backLockTime)
  } else {
    that.delayConfig.backPress.type = true
  }
  console.log(that.delayConfig.backPress.type, 'backPress--------添加拦截')
}
// 音频播放
const playAudio = () => {
  // 音效处理 判断当前是否开启音效
  if (
    that.curpopConfig.commonStyle.isOpenAudio &&
    that.curpopConfig.commonStyle.mp3SoundEffect
  ) {
    try {
      audio.src = that.curpopConfig.commonStyle.mp3SoundEffect
      audio.play()
    } catch (error) {
      LOG('VIEW', '音频播放失败', error)
    }
  }
}
// 弹窗展示上报
const reportShowPop = () => {
  //弹窗展示上报
  AD_SDK.ad_sdk_global.popShowNum++
  let param = {
    ad_network: that.nativeAdvObj.ad_network,
    page_type: that.curpopConfig.popGroupName,
    ad_position: that.curpopConfig.popName,
    ad_style: AD_SDK.ad_sdk_global.popShowNum + '',
    page_name: '有',
    ext_field_9: that.action2Name(that.actionCode),
    ext_field_2: that.nativeAdvObj.layer >= 0 ? that.nativeAdvObj.layer + 1 + '' : '1',
    ad_type: that.nativeAdvObj.ad_type,
    ad_id: that.nativeAdvObj.id,
    referer: '有广告弹窗',
    scene: that.nativeAdvObj.scene,
    ext_field_8: that.nativeAdvObj.advDetail ? that.nativeAdvObj.advDetail.appInfo ? that.nativeAdvObj.advDetail.appInfo.appName : that.nativeAdvObj.advDetail.appName || that.nativeAdvObj.title || that.nativeAdvObj.advDetail.title : '',
    ext_field_1: that.nativeAdvObj.isBidding && that.nativeAdvObj.advDetail ? that.nativeAdvObj.advDetail.ecpm + '' : ''
  }
  COMMON_REPORT_UTILS.custom_popup_show_report(
    param.ad_network,
    param.page_type,
    param.ad_position,
    param.ad_style,
    param.page_name,
    param.ext_field_9,
    param.ext_field_2,
    param.ad_id,
    param.scene,
    param.referer,
    param.ad_type,
    param.ext_field_8,
    param.ext_field_1
  )
}
const popBeforeShowGif = (obj) => {
  // 展示gif图
  if (obj) {
    that.popShowGifImg = obj.commonStyle.transitionBeforeImg
    if (obj.commonStyle.transitionBeforeTime) {
      that.popShowGif = true
      setTimeout(() => {
        that.popShowGif = false
        playAudio()
      }, Number(obj.commonStyle.transitionBeforeTime))
    } else {
      playAudio()
      that.popShowGif = false
    }
  }
}
const getMenuData = () => {
  try {
    let menuBarRect = that.$page.getMenuBarRect()
    if (menuBarRect && menuBarRect.menuBarWidth > 0) {
      device.getInfo({
        success: function (ret) {
          try {
            let radio = 750 / ret.screenWidth
            that.menuBarRight = keepTwoDecimal(
              750 - menuBarRect.menuBarRight * radio
            )
            that.menuBarHeight = menuBarRect.menuBarHeight
            that.menuBarWidth = keepTwoDecimal(menuBarRect.menuBarWidth * radio)
            that.menuBarTop = keepTwoDecimal(menuBarRect.menuBarTop * radio)
            console.log(menuBarRect, 'sfasfsfsdfdsfds')
          } catch (err) { }
        },
      })
    }
  } catch (e) { }
}
const keepTwoDecimal = (num) => {
  var result = parseFloat(num)
  if (isNaN(result)) {
    return false
  }
  return Math.round(num * 100) / 100
}
const popUtil = {
  getCodeData
}
export default popUtil
